package com.inossem.allotin.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.inossem.allotin.InossemApplication;
import com.inossem.allotin.constant.UrlConstant;
import com.inossem.wms.model.biz.BizReceiptAttachmentVo;
import com.inossem.wms.model.file.LogFile;
import com.inossem.wms.vo.dic.DicUnitDecimalPlaceVo;
import com.orhanobut.logger.Logger;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.inossem.allotin.constant.ItemStatusConstant.YEAR_MONTH_DAY;

/**
 * 工具类
 *
 * @author 詹建宇
 * @time on 2018/12/14 10:26
 * @email jianyu.zhan@inossem.com
 */
public class Utils {

    /**
     * 显示图片
     * type org:原图 web:web缩略图 pad:pad缩略图
     */
    public static final String ORG = "org";
    public static final String WEB = "web";
    public static final String PAD = "pad";

    /**
     * 关闭软键盘
     */
    public static void closeSoftKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 判断是否是数字 并且不为负数
     */
    public static Boolean isPositiveNumber(String num) {
        return !TextUtils.isEmpty(num) && num.matches("-?[0-9]+.*[0-9]*") && new BigDecimal(num).compareTo(BigDecimal.ZERO) != -1;
    }

    /**
     * 判断是否为0
     */
    public static Boolean isZero(String num) {
        if (TextUtils.isEmpty(num)) {
            return false;
        }
        Pattern p = Pattern.compile("^0+(\\.?0+)?$");
        Matcher m = p.matcher(num);
        return m.matches();
    }

    /**
     * 获取该单位下 小数位数
     */
    public static byte getDecimalPlace(String unitCode) {
        if (TextUtils.isEmpty(unitCode)) return 0;
        List<DicUnitDecimalPlaceVo> unitList = ACacheUtils.getUnitList();
        for (DicUnitDecimalPlaceVo vo : unitList) {
            if (unitCode.equals(vo.getUnitCode())) return vo.getDecimalPlace();
        }
        return 0;
    }

    /**
     * 设置TextView左侧图片 及图片尺寸
     */
    public static void setDrawableLeft(TextView textView, int drawableId, float width, float height) {
        if (null == textView) return;
        Context context = textView.getContext();
        Drawable left = ContextCompat.getDrawable(context, drawableId);
        left.setBounds(0, 0, (int) DensityHelper.pt2px(context, width), (int) DensityHelper.pt2px(context, height));
        textView.setCompoundDrawables(left, null, null, null);
    }

    /**
     * 检查网络是否可用
     */
    public static boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) InossemApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        assert connectivityManager != null;
        NetworkInfo networkinfo = connectivityManager.getActiveNetworkInfo();
        return null != networkinfo && networkinfo.isConnected();
    }

    public static void showSubmitImg(ImageView imageView, String imgCode) {
        String url = ACacheUtils.getProtocol() + ACacheUtils.getDomain() + ":" + ACacheUtils.getPort()
                + UrlConstant.DEFAULT_PATH + UrlConstant.URL_FILE_SHOW + "/" + imgCode;
        Logger.i(url);
        Glide.with(imageView.getContext()).load(url).into(imageView);
    }

    /**
     * LogFile->BizReceiptAttachmentVo 保持Bean类统一
     */
    public static List<BizReceiptAttachmentVo> changeLogFileToBizReceiptAttachmentVo(List<LogFile> list) {
        List<BizReceiptAttachmentVo> resultList = new ArrayList<>();
        for (LogFile logFile : list) {
            BizReceiptAttachmentVo resultBean = new BizReceiptAttachmentVo();
            resultBean.setFileCode(logFile.getFileCode());
            resultBean.setBizReceiptAttachmentId(0);
            resultList.add(resultBean);
        }
        return resultList;
    }

    /**
     * 必填项TextView处理
     */
    public static void mustTextView(TextView tv) {
        String value = tv.getText() + "*";
        SpannableStringBuilder builder = new SpannableStringBuilder(value);
        ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
        builder.setSpan(redSpan, value.length() - 1, value.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(builder);
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }


    public static Integer getVersionCode(Context context) {
        Integer result = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0);
            result = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        //显示软键盘
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        assert imm != null;
        imm.showSoftInput(editText, 0);
    }

    /**
     * 文件转bitmap
     */
    public static Bitmap fileToBitmap(String path) {
        try {
            return BitmapFactory.decodeFile(path);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 设置TextView最多几行 末尾省略号
     */
    public static void setTextLine(TextView textView, int line) {
        textView.setMaxLines(line);
        textView.setEllipsize(TextUtils.TruncateAt.END);
    }

    /**
     * 设置view中的子TextView行数 和末尾省略号
     */
    public static void setViewLine(View view) {
        List<View> viewList = getAllChildViews(view);
        for (View viewChild : viewList) {
            if (viewChild instanceof TextView) {
                setTextLine((TextView) viewChild, 2);
            }
        }
    }

    /**
     * 获取view下所有空间
     */
    public static List<View> getAllChildViews(View view) {
        List<View> allChildren = new ArrayList<>();
        if (view instanceof ViewGroup) {
            ViewGroup vp = (ViewGroup) view;
            for (int i = 0; i < vp.getChildCount(); i++) {
                View viewChild = vp.getChildAt(i);
                allChildren.add(viewChild);
                //再次 调用本身（递归）
                allChildren.addAll(getAllChildViews(viewChild));
            }
        }
        return allChildren;
    }

    /**
     * 设置activity下字体大小
     */
    public static void setViewFontSize(Activity activity) {
        List<View> viewList = getAllChildViews(activity.getWindow().getDecorView());
        for (View viewChild : viewList) {
            if (viewChild instanceof TextView) {
                ((TextView) viewChild).setTextSize(15);
            }
        }
    }

    /**
     * 按钮显示隐藏 0隐藏 1显示
     */
    public static void setButtonStatus(View view, byte status) {
        if (null == view) return;
        switch (status) {
            case 0:
                view.setVisibility(View.GONE);
                break;
            case 1:
                view.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    public static String systemData() {
        SimpleDateFormat sdf = new SimpleDateFormat(YEAR_MONTH_DAY, Locale.CHINESE);
        return sdf.format(System.currentTimeMillis());
    }

    /**
     * 从附件列表总 获取图片列表
     */
    public static List<BizReceiptAttachmentVo> getPicListFromFiles(List<BizReceiptAttachmentVo> files) {
        if (null == files || files.isEmpty()) return new ArrayList<>();
        String[] picFormats = new String[]{"bmp", "jpg", "jpeg", "png", "BMP", "JPG", "JPEG", "PNG"};
        List<BizReceiptAttachmentVo> resultList = new ArrayList<>();
        for (BizReceiptAttachmentVo file : files) {
            for (String picFormat : picFormats) {
                if (!TextUtils.isEmpty(file.getFileExt()) && file.getFileExt().contains(picFormat)) {
                    resultList.add(file);
                    break;
                }
            }
        }
        return resultList;
    }

    /**
     * 按钮宽度
     */
    public static void setButtonWidth(View view, byte status) {
        ViewGroup.LayoutParams linearParams = view.getLayoutParams();
        switch (status) {
            case 0:
                linearParams.width = 0;
                view.setLayoutParams(linearParams);
                break;
            case 1:
                linearParams.width = 200;
                view.setLayoutParams(linearParams);
                break;
            default:
                break;
        }
    }

    /**
     * Bitmap转File
     */
    public static File bitmapToFile(Bitmap bitmap) {
        String name = String.valueOf(TimeUtils.getTimeSeal());
        String imagePath = "Inossem_Signature";
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + imagePath + File.separator + name + ".png";
        File file = new File(filePath);// 将要保存图片的路径
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static void setEditTextEnable(EditText editText, boolean isEdit) {
        editText.setCursorVisible(isEdit);
        editText.setEnabled(isEdit);
        editText.setFocusable(isEdit);
        editText.setFocusableInTouchMode(isEdit);
    }

    /**
     * 设置语言
     *
     * @param lauType
     */
    public static void setLanguage(Context context, String lauType) { // 本地语言设置
        Locale myLocale = new Locale(lauType);
        Resources res = context.getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
    }

    //获取系统语言
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    //将字节转成B或KB或MB或GB，保留2位小时
    public static String getPrintSize(long size) {
        //如果字节数少于1024，则直接以B为单位，否则先除于1024，后3位因太少无意义
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }
        //如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位
        //因为还没有到达要使用另一个单位的时候
        //接下去以此类推
        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            //因为如果以MB为单位的话，要保留最后1位小数，
            //因此，把此数乘以100之后再取余
            size = size * 100;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "MB";
        } else {
            //否则如果要以GB为单位的，先除于1024再作同样的处理
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "GB";
        }
    }

    /**
     * 获取保存签名的目录
     *
     * @return
     */
    public static File getSignDir(Context context) {
        File dir = new File(getRootPath(context), "Emergency" + File.separator + "Sign");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 获取保存文件的目录
     *
     * @return
     */
    public static File getFileDir(Context context) {
        File dir = new File(getRootPath(context), "Emergency" + File.separator + "File");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 获取照片名
     *
     * @return
     */
    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMddHHmmssSSS");
        return dateFormat.format(date) + ".jpg";
    }

    /**
     * 删除单个文件
     * @param   filePath    被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }
    /**
     * 得到SD卡根目录.
     */
    public static File getRootPath(Context context) {
        if (sdCardIsAvailable()) {
            return Environment.getExternalStorageDirectory(); // 取得sdcard文件路径
        } else {
            return context.getFilesDir();
        }
    }

    /**
     * SD卡是否可用.
     */
    public static boolean sdCardIsAvailable() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sd = new File(Environment.getExternalStorageDirectory().getPath());
            return sd.canWrite();
        } else
            return false;
    }

    /**
     * 检查互联网地址是否可以访问-使用get请求
     *
     * @param urlStr   要检查的url
     * @param callback 检查结果回调（是否可以get请求成功）{@see java.lang.Comparable<T>}
     */
    public static void isNetWorkAvailableOfGet(final String urlStr, final Comparable<Boolean> callback) {
        final Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (callback != null) {
                    callback.compareTo(msg.arg1 == 0);
                }
            }

        };
        new Thread(new Runnable() {

            @Override
            public void run() {
                Message msg = new Message();
                try {
                    Connection conn = new Connection(urlStr);
                    Thread thread = new Thread(conn);
                    thread.start();
                    thread.join(3 * 1000); // 设置等待DNS解析线程响应时间为3秒
                    int resCode = conn.get(); // 获取get请求responseCode
                    msg.arg1 = resCode == 200 ? 0 : -1;
                } catch (Exception e) {
                    msg.arg1 = -1;
                    e.printStackTrace();
                } finally {
                    handler.sendMessage(msg);
                }
            }

        }).start();
    }

    /**
     * HttpURLConnection请求线程
     */
    private static class Connection implements Runnable {
        private String urlStr;
        private int responseCode;

        public Connection(String urlStr) {
            this.urlStr = urlStr;
        }

        public void run() {
            try {
                URL url = new URL(urlStr);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.connect();
                set(conn.getResponseCode());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public synchronized void set(int responseCode) {
            this.responseCode = responseCode;
        }

        public synchronized int get() {
            return responseCode;
        }
    }

}
